package com.example.backed.service.impl;

import com.example.backed.dto.OrderCreateDTO;
import com.example.backed.dto.OrderQueryDTO;
import com.example.backed.entity.CartItem;
import com.example.backed.entity.Order;
import com.example.backed.entity.OrderItem;
import com.example.backed.entity.Product;
import com.example.backed.exception.BusinessException;
import com.example.backed.mapper.CartItemMapper;
import com.example.backed.mapper.OrderItemMapper;
import com.example.backed.mapper.OrderMapper;
import com.example.backed.mapper.ProductMapper;
import com.example.backed.service.OrderService;
import com.example.backed.vo.OrderStatsVO;
import com.example.backed.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final CartItemMapper cartItemMapper;
    private final ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Long userId, OrderCreateDTO createDTO) {
        // 1. 获取用户购物车中已选中的商品
        List<CartItem> cartItems = cartItemMapper.findSelectedByUserId(userId);
        if (cartItems.isEmpty()) {
            throw new BusinessException("购物车中没有选中的商品");
        }

        // 2. 检查商品库存
        for (CartItem cartItem : cartItems) {
            Product product = productMapper.findById(cartItem.getProductId());
            if (product == null) {
                throw new BusinessException("商品不存在");
            }
            if (product.getStatus() != 1) {
                throw new BusinessException("商品已下架");
            }
            if (product.getStock() < cartItem.getQuantity()) {
                throw new BusinessException("商品库存不足");
            }
        }

        // 3. 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setStatus(1); // 已支付
        order.setAddress(createDTO.getAddress());
        order.setReceiver(createDTO.getReceiver());
        order.setPhone(createDTO.getPhone());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        // 4. 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (CartItem cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductName(cartItem.getProductName());
            orderItem.setProductImage(cartItem.getProductImage());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalAmount(cartItem.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
            orderItem.setCreateTime(LocalDateTime.now());
            orderItem.setUpdateTime(LocalDateTime.now());
            
            totalAmount = totalAmount.add(orderItem.getTotalAmount());
            orderItems.add(orderItem);

            // 5. 扣减库存
            productMapper.decreaseStock(cartItem.getProductId(), cartItem.getQuantity());
        }

        order.setTotalAmount(totalAmount);
        orderMapper.insert(order);

        // 6. 保存订单项
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
        }
        orderItemMapper.batchInsert(orderItems);

        // 7. 清空购物车已选中的商品
        cartItemMapper.deleteSelectedByUserId(userId);

        return order;
    }

    @Override
    public Order getOrderById(Long id) {
        Order order = orderMapper.findById(id);
        if (order != null) {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(id);
            order.setOrderItems(orderItems);
        }
        return order;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        Order order = orderMapper.findByOrderNo(orderNo);
        if (order != null) {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
            order.setOrderItems(orderItems);
        }
        return order;
    }

    @Override
    public PageVO<Order> getOrderList(OrderQueryDTO query) {
        // 1. 查询总数
        int total = orderMapper.countByQuery(query);
        if (total == 0) {
            return PageVO.empty();
        }

        // 2. 查询数据
        List<Order> orders = orderMapper.findByQuery(query);
        if (!orders.isEmpty()) {
            // 3. 查询订单项
            List<Long> orderIds = orders.stream().map(Order::getId).toList();
            List<OrderItem> orderItems = orderItemMapper.findByOrderIds(orderIds);

            // 4. 组装数据
            for (Order order : orders) {
                List<OrderItem> items = orderItems.stream()
                        .filter(item -> item.getOrderId().equals(order.getId()))
                        .toList();
                order.setOrderItems(items);
            }
        }

        // 5. 返回结果
        return new PageVO<>(orders, total, query.getPageNum(), query.getPageSize());
    }

    @Override
    public PageVO<Order> getUserOrderList(Long userId, OrderQueryDTO query) {
        // 1. 查询总数
        int total = orderMapper.countByUserId(userId, query);
        if (total == 0) {
            return PageVO.empty();
        }

        // 2. 查询数据
        List<Order> orders = orderMapper.findByUserId(userId, query);
        if (!orders.isEmpty()) {
            // 3. 查询订单项
            List<Long> orderIds = orders.stream().map(Order::getId).toList();
            List<OrderItem> orderItems = orderItemMapper.findByOrderIds(orderIds);

            // 4. 组装数据
            for (Order order : orders) {
                List<OrderItem> items = orderItems.stream()
                        .filter(item -> item.getOrderId().equals(order.getId()))
                        .toList();
                order.setOrderItems(items);
            }
        }

        // 5. 返回结果
        return new PageVO<>(orders, total, query.getPageNum(), query.getPageSize());
    }

    @Override
    public boolean updateOrderStatus(Long userId, Long orderId, Integer status) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        return orderMapper.updateStatus(orderId, status) > 0;
    }

    @Override
    public Order getOrderDetail(Long userId, Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        return order;
    }

    @Override
    public List<Order> getUserOrders(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long userId, Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 0) {
            throw new BusinessException("只能取消待支付的订单");
        }

        // 1. 更新订单状态
        orderMapper.updateStatus(orderId, 4); // 已取消

        // 2. 恢复商品库存
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            productMapper.increaseStock(orderItem.getProductId(), orderItem.getQuantity());
        }

        return true;
    }

    @Override
    public boolean deleteOrder(Long userId, Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() == 1 || order.getStatus() == 2) {
            throw new BusinessException("已支付或已发货的订单不能删除");
        }

        // 删除订单项
        orderItemMapper.deleteByOrderId(orderId);
        return true;
    }

    @Override
    public OrderStatsVO getOrderStats() {
        OrderStatsVO stats = new OrderStatsVO();
        
        // 1. 获取所有订单统计
        List<Order> allOrders = orderMapper.findOrderStats();
        for (Order order : allOrders) {
            stats.setTotalOrders(stats.getTotalOrders() + 1);
            stats.setTotalAmount(stats.getTotalAmount().add(order.getTotalAmount()));
            
            switch (order.getStatus()) {
                case 0 -> stats.setPendingPaymentOrders(stats.getPendingPaymentOrders() + 1);
                case 1 -> stats.setPaidOrders(stats.getPaidOrders() + 1);
                case 2 -> stats.setShippedOrders(stats.getShippedOrders() + 1);
                case 3 -> stats.setCompletedOrders(stats.getCompletedOrders() + 1);
                case 4 -> stats.setCancelledOrders(stats.getCancelledOrders() + 1);
            }
        }

        // 2. 获取今日订单统计
        List<Order> todayOrders = orderMapper.findTodayOrders();
        for (Order order : todayOrders) {
            stats.setTodayOrders(stats.getTodayOrders() + 1);
            stats.setTodayAmount(stats.getTodayAmount().add(order.getTotalAmount()));
        }

        return stats;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
} 